package com.hengx.cellview.app;

import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
import static com.hengx.cellview.app.Post.*;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.ViewGroup;

import androidx.appcompat.app.AppCompatActivity;

import com.hengx.cellview.CellMap;
import com.hengx.cellview.CellView;
import com.hengx.cellview.cell.Cell;
import com.hengx.cellview.cell.CellGroup;
import com.hengx.cellview.cell.CheckBoxCell;
import com.hengx.cellview.cell.ColorCell;
import com.hengx.cellview.cell.DrawableCell;
import com.hengx.cellview.cell.TextCell;

import java.util.Random;

public class MainActivity extends AppCompatActivity {
    
    private CellView cellView;
    private CellMap cellMap;
    
    private String[][] cells = {
        // 标签行
        { "ID", "昵称", "特征", "年龄", "职业", "爱好", "居住地", "是否逆天", "社交媒体账号", "宠物" },
        // 数据行
        { "1", "蔡徐坤", "喜欢唱、跳、Rap、打篮球", "22", "歌手", "音乐", "北京", "true", "KunCai", "猫" },
        { "2", "张三", "法外狂徒", "30", "自由职业者", "旅游", "上海", "false", "ZhangSan", "狗" },
        { "3", "铜人", "该罚！", "28", "演员", "表演艺术", "广州", "false", "TongRen", "鹦鹉" },
        { "4", "阿恒", "玩原神玩的", "1", "魔怔人", "电子游戏", "地球", "true", "ShenJin", "黑子" },
        { "5", "李四", "擅长编程", "0", "程序员", "编程", "杭州", "true", "LiSi", "乌龟" },
        { "6", "歌裴莉娅", "女铜机关人", "?", "冰风组曲", "凤凰传奇", "枫丹", "true", "XiatouNv", "旅行者" },
        { "7", "科培琉司", "男铜机关人", "?", "冰风组曲", "凤凰传奇", "枫丹", "true", "XiatouNan", "旅行者" },
        { "8", "多托雷", "提瓦特传奇医德圣人", "?", "「博士」", "做人", "至冬", "true", "Doctor", "魔神残渣" },
        { "9", "周八", "喜欢旅行", "26", "旅行博主", "探险", "武汉", "false", "ZhouBa", "仓鼠" },
        { "10", "吴九", "热爱音乐", "24", "音乐制作人", "制作音乐", "天津", "创造性", "WuJiu", "蜥蜴" },
        { "11", "郑十", "喜欢绘画", "32", "画家", "绘画", "苏州", "艺术感", "ZhengShi", "猫头鹰" },
        { "12", "王十一", "喜欢健身", "29", "健身教练", "健身", "青岛", "活力", "WangShiYi", "狗" },
        { "13", "陈十二", "喜欢写作", "34", "记者", "写作", "大连", "好奇心强", "ChenShiEr", "鹦鹉" },
        { "14", "刘十三", "喜欢科学", "38", "科学家", "研究", "宁波", "智慧", "LiuShiSan", "龟" },
        { "15", "郭十四", "喜欢作死", "23", "探险家", "探险", "厦门", "勇敢", "GuoShiSi", "蛇" },
        { "16", "马十五", "喜欢编程", "28", "软件工程师", "编程", "合肥", "逻辑思维强", "MaShiWu", "金鱼" },
        { "17", "不知道", "喜欢阅读", "33", "图书管理员", "阅读", "南昌", "知识渊博", "XuShiLiu", "兔子" },
        { "18", "何十七", "喜欢运动", "22", "运动员", "各种运动", "昆明", "活力充沛", "HeShiQi", "鹦鹉" },
        { "19", "吕十八", "喜欢电影", "40", "电影导演", "电影制作", "福州", "创意无限", "LvShiBa", "狗" },
        { "20", "施十九", "喜欢音乐", "25", "音乐家", "演奏乐器", "济南", "情感丰富", "ShiShiJiu", "猫" },
        { "21", "张二十", "喜欢旅行", "31", "旅行博主", "环游世界", "长春", "冒险精神", "ZhangErShi", "鱼" },
        { "22", "吴二十一", "喜欢摄影", "29", "摄影师", "捕捉瞬间", "哈尔滨", "观察细致", "WuErShiYi", "仓鼠" },
        { "23", "周二十二", "喜欢艺术", "27", "艺术家", "创作艺术", "石家庄", "想象力丰富", "ZhouErShiEr", "鸟" },
        { "24", "郑二十三", "喜欢科学", "35", "科学家", "科学实验", "太原", "逻辑严谨", "ZhengErShiSan", "蜥蜴" },
        { "25", "王二十四", "喜欢历史", "30", "历史学家", "研究历史", "兰州", "博学多识", "WangErShiSi", "龟" }
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.cellView = new CellView(this);
        cellView.setPadding(dip2px(16), dip2px(16), dip2px(16), dip2px(32));
        cellView.setLayoutParams(new ViewGroup.LayoutParams(-1, -1));
        setContentView(cellView);
        this.cellMap = new CellMap(cells[0].length, cells.length);
        for (int y = 0; y < cells.length; y++) {
            String[] line = cells[y];
            for(int x = 0; x < line.length; x++) {
                if (line[x] == null) continue;
                CellGroup group = new CellGroup();
                if (x == 7 && y > 0) {
                    CheckBoxCell cell = new CheckBoxCell();
                    cell.setChecked(line[x].equals("true"));
                    //cell.setGravity(Gravity.LEFT);
                    if (y % 2 == 1) {
                        group.add(new ColorCell(0x10808080));
                    }
                    group.add(cell);
                } else {
                    TextCell cell = new TextCell(line[x], 0xff333333);
                    if (y == 0) {
                        //是第一行，要高亮
                        cell.setBackgroundColor(0xff009bff);
                        cell.setTextColor(0xffffffff);
                    }
                    if (y % 2 == 1) {
                        //是奇数行
                        cell.setBackgroundColor(0x10808080);
                    }
                    group.add(cell);
                }
                group.add(new DrawableCell(getWaterDrawable()));
                cellMap.set(x, y, group);
            }
        }
        cellView.setWidth(2, dip2px(200)); // 特征列
        cellView.setWidth(5, dip2px(120)); // 爱好列
        cellView.setWidth(7, dip2px(80)); // 是否逆天列
        cellView.setWidth(8, dip2px(140)); // 社交媒体账号列
        cellView.setScrollBoundaryEnabled(true);
        cellView.setScalable(true);
        cellView.setClickable(true);
        cellView.setData(cellMap);
        cellView.invalidate();
        cellView.setOnCellClickListener((x, y) -> {
            try {
            Cell cell = cellMap.get(x, y);
            Cell[] cells;
            if (cell instanceof CellGroup) {
                CellGroup group = (CellGroup) cell;
                cells = new Cell[group.getCount()];
                for(int i = 0; i < cells.length; i++) {
                    cells[i] = group.get(i);
                }
            } else {
                cells = new Cell[] {cell};
            }
            for(Cell c : cells) {
                if (c instanceof TextCell)
                    postText(this, "单击：" + ((TextCell)c).getText());
                else if (c instanceof CheckBoxCell) {
                    ((CheckBoxCell)c).setChecked(!((CheckBoxCell)c).isChecked());
                    cellView.invalidate();
                }
            }
            }catch(Throwable e){
                postText(this, e.toString());
            }
        });
        cellView.setOnCellLongClickListener((x, y) -> {
            Cell cell = cellMap.get(x, y);
            Cell[] cells;
            if (cell instanceof CellGroup) {
                CellGroup group = (CellGroup) cell;
                cells = new Cell[group.getCount()];
                for(int i = 0; i < cells.length; i++) {
                    cells[i] = group.get(i);
                }
            } else {
                cells = new Cell[] {cell};
            }
            for(Cell c : cells) {
                if (c instanceof TextCell)
                    postText(this, "长按：" + ((TextCell)c).getText());
            }
        });
    }
    
    public Drawable getWaterDrawable() {
    	Resources.Theme theme = getTheme();
        TypedValue typedValue = new TypedValue();
        theme.resolveAttribute(android.R.attr.selectableItemBackground, typedValue, true);
        int[] attribute = new int[] { android.R.attr.selectableItemBackground };
        TypedArray typedArray = theme.obtainStyledAttributes(typedValue.resourceId, attribute);
        return typedArray.getDrawable(0);
    }
    
    /**
     * dip转px
     * @param context 上下文
     * @param value 值
     * @return 结果
     */
    public int dip2px(int value){
        return (int) (value * getResources().getDisplayMetrics().density + 0.5f);
    }
    
    /**
     * 生成指定范围内的随机整数。
     * @param min 最小值（包含）
     * @param max 最大值（不包含）
     * @return 范围内的随机整数
     */
    public static int randomInt(int min, int max) {
        if (min >= max) {
            throw new IllegalArgumentException("最小值必须小于最大值");
        }
        Random random = new Random();
        return random.nextInt(max - min) + min;
    }
    
    /**
     * 生成随机颜色值，透明度为最大。
     * @return 随机颜色的ARGB值
     */
    public static int randomColor() {
        // 生成红色、绿色和蓝色分量的随机值，范围从0到255
        int red = (int)(Math.random() * 256);
        int green = (int)(Math.random() * 256);
        int blue = (int)(Math.random() * 256);
        
        // Alpha值设置为255，表示完全不透明
        int alpha = 255;
        
        // 使用Color.argb()方法生成ARGB颜色值
        return Color.argb(alpha, red, green, blue);
    }

}
